package com.zhh.dataservice.service;

import com.zhh.api.model.BidInfo;
import com.zhh.api.model.FinanceAccount;
import com.zhh.api.model.ProductInfo;
import com.zhh.api.model.RechargeRecord;
import com.zhh.api.pojo.BidInfoProduct;
import com.zhh.api.service.InvestService;
import com.zhh.common.contants.FMContants;
import com.zhh.common.util.CommonUtil;
import com.zhh.dataservice.mapper.BidInfoMapper;
import com.zhh.dataservice.mapper.FinanceAccountMapper;
import com.zhh.dataservice.mapper.ProductInfoMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService(interfaceClass = InvestService.class,version="1.0")
public class InvestServiceImpl implements InvestService {

    @Resource
    BidInfoMapper bidInfoMapper;

    @Resource
    FinanceAccountMapper financeAccountMapper;

    @Resource
    ProductInfoMapper productInfoMapper;

    //查询某个产品的投资记录
    @Override
    public List<BidInfoProduct> queryBidListByProductId(Integer productId,
                                                        Integer pageNo,
                                                        Integer pageSize) {

        List<BidInfoProduct> bidList = new ArrayList<>();
        if(productId != 0 && productId > 0){
            pageNo = CommonUtil.defaultPageNo(pageNo);
            pageSize = CommonUtil.defaultPageSize(pageSize);
            int offset = (pageNo - 1) * pageSize;
            bidList = bidInfoMapper.selectByProductId(productId,offset,pageSize);
        }
        return bidList;
    }

    //在用户中心查询投资记录
    @Override
    public List<BidInfo> queryByUid(Integer uid, Integer pageNo, Integer pageSize) {
        //储存记录
        List<BidInfo> records = new ArrayList<>();
        //验证数据
        if(uid != null && uid > 0){
            pageNo = CommonUtil.defaultPageNo(pageNo);
            pageSize = CommonUtil.defaultPageSize(pageSize);
            int offset = (pageNo-1) * pageSize;

            //用分页查询，通过uid查询充值记录
            records = bidInfoMapper.selectByUid(uid,offset,pageSize);
        }
        return records;
    }

    //购买理财产品
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int investProduct(Integer uid, Integer productId, BigDecimal money) {
        int result = 0;
        int rows;

        //1.参数检查
        if ((uid != null && uid > 0) && (productId != null && productId > 0) && (money != null && money.intValue() % 100 == 0 && money.intValue() >= 100)) {

            //2.查询账号金额
            FinanceAccount account = financeAccountMapper.selectByUidForUpdate(uid);
            if(account!=null){
                //比较用户资金是否满足购买需求
                if(CommonUtil.ge(account.getAvailableMoney(),money)){

                    //资金满足购买要求
                    //3.检查产品是否可以购买
                    ProductInfo productInfo = productInfoMapper.selectByPrimaryKey(productId); //查询理财产品
                    if (productInfo != null && productInfo.getProductStatus() == FMContants.PRODUCT_STATUS_SELLING) { //查看理财产品是否存在，并且是否已经满标
                        //比较投资资金是否 大于剩余可投金额，大于最小可投金额，小于最大可投金额
                        if (CommonUtil.ge(productInfo.getLeftProductMoney(), money) &&
                                CommonUtil.ge(money, productInfo.getBidMinLimit()) &&
                                CommonUtil.ge(productInfo.getBidMaxLimit(), money)){
                            //所有条件满足，可以购买产品了
                            //4.扣除账号资金
                            rows = financeAccountMapper.updateAvailableMoneyByInvest(uid,money);
                            if(rows < 1){
                                throw new RuntimeException("更新账号资金失败"); //事务回滚
                            }

                            //5.扣除产品剩余可投资金额
                            rows = productInfoMapper.updateLeftProductMoney(productId,money);
                            if(rows < 1){
                                throw new RuntimeException("更新产品剩余可投资金额失败"); //事务回滚
                            }

                            //6.添加投资记录
                            BidInfo bidInfo = new BidInfo();
                            bidInfo.setBidMoney(money);
                            bidInfo.setBidStatus(FMContants.INVEST_STATUS_SUCC);
                            bidInfo.setBidTime(new Date());
                            bidInfo.setLoanId(productId);
                            bidInfo.setUid(uid);
                            bidInfoMapper.insertSelective(bidInfo);

                            //7.判断产品是否卖完，更新产品的可投资金额
                            //再次查看产品
                            ProductInfo dbproductInfo = productInfoMapper.selectByPrimaryKey(productId);
                            //查看产品剩余可投资金额是否为零
                            if(dbproductInfo.getLeftProductMoney().compareTo(new BigDecimal("0")) == 0){
                                //产品剩余可投资金额为零，更新产品为满标
                                rows = productInfoMapper.updateSelled(productId);
                                if( rows < 1 ){
                                    throw new RuntimeException("投资更新产品满标失败");
                                }
                            }

                            //8.投资成功
                            result = 1;

                        }else{
                            result = 5; //剩余金额不足
                        }
                    }else{
                        result = 4; //理财产品不存在
                    }
                }else{
                    result = 3; //账户资金不足
                }
            }else{
                result = 2; //资金账号不存在
            }
        }
        return result;
    }
}

